package com.l024.hi_device_util.device;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @author wu_ming_zhi_bei
 * @date 2021/6/1 10:53
 * @Notes 设备数据获取工具类
 */
public class DeviceUtil {

   private static class DeviceHoler{
        private static DeviceUtil instance = new DeviceUtil();
   }
   private DeviceUtil(){}

   //饿汉式单例
   public static DeviceUtil getInstance(){
       return DeviceHoler.instance;
   }
    public static String permission = Manifest.permission.READ_PHONE_STATE;
    public static final int DEVICE_CODE = 1000;
    private Context context;
    private OnGaidListener onGaidListener;
    //gaid监听
    public interface OnGaidListener{
        void onSuccess(DeviceModel deviceModel);
    }

    public void setOnGaidListener(OnGaidListener onGaidListener) {
        this.onGaidListener = onGaidListener;
    }

    /**
     * 获取手机号码
     */
    @SuppressLint("HardwareIds")
    public void getDeviceInfo(Context context,OnGaidListener listener){
        this.context = context;
        this.onGaidListener = listener;
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if(tm==null){
            return;
        }
        final DeviceModel deviceModel = new DeviceModel();
        deviceModel.setImsi(getImsi(context));
        deviceModel.setPhone(tm.getLine1Number());
        deviceModel.setImei(getImei(context));
        deviceModel.setAndroidId(getAndroidId(context));
        deviceModel.setMacAddress(getMacAddress(context));
        deviceModel.setVersion(android.os.Build.VERSION.RELEASE);
        GaidAsyncTask gaidAsyncTask = new GaidAsyncTask();
        gaidAsyncTask.execute(deviceModel);
    }

    public DeviceModel getDeviceInfo2(final Context context){
        this.context = context;
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final DeviceModel deviceModel = new DeviceModel();
        if(tm==null){
            return deviceModel;
        }
        deviceModel.setImsi(getImsi(context));
        deviceModel.setPhone(tm.getLine1Number());
        deviceModel.setImei(getImei(context));
        deviceModel.setAndroidId(getAndroidId(context));
        deviceModel.setMacAddress(getMacAddress(context));
        deviceModel.setVersion(android.os.Build.VERSION.RELEASE);
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                try {
                    //AdvertisingIdClient.AdInfo adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context);
                    //String gaid = adInfo.getId();
                    //System.out.println("gaid--->"+gaid);
                    return "ds4dds4sdsds";
                }catch (Exception e){
                    Log.e("获取gaid失败:",e.getMessage());
                }
                return "";
            }
        };
        FutureTask<String> ft1 = new FutureTask<String>(callable);
        //ExecutorService  service = Executors.newCachedThreadPool();
        //service.execute(ft1);
        new Thread(ft1).start();
        try {
            deviceModel.setGaid(ft1.get());
        }catch (Exception e){
            Log.e("线程获取gaid失败",e.toString());
        }
        return deviceModel;
    }

    //当前设备(手机)全世界唯一的id
    public String getImei(Context context){
        String imei = "";
        TelephonyManager tm = (TelephonyManager) context.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
        //判断api版本
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                imei = Settings.System.getString(
                        context.getContentResolver(), Settings.Secure.ANDROID_ID);
            }else{
                //判断是否大于等于10
                if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.Q){
                    imei = Settings.System.getString(
                            context.getContentResolver(), Settings.Secure.ANDROID_ID);
                    //判断是否大于等于8
                }else if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
                    imei = tm.getImei();
                    if(TextUtils.isEmpty(imei)){
                        imei = tm.getDeviceId();
                    }
                }else{
                    //5.0使用
                    imei = tm.getDeviceId();
                }
            }

        }else{
            //5.0以下
            imei = tm.getDeviceId();
        }
        return imei;
    }
    //获取androidid
    public String getAndroidId(Context context){
        return Settings.System.getString(
                context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }
    //获取imsi
    public String getImsi(Context context){
        TelephonyManager tm = (TelephonyManager) context.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
        //大于10直接返回
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.Q){
            return "";
        }
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            if (context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return "";
            }else{
                return tm.getSubscriberId();
            }
        }else{
            return tm.getSubscriberId();
        }
    }

    //获取mac
    public String getMacAddress(Context context){
        String mac = "";
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            mac = MacUtil.getMacDefault(context);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            mac = MacUtil.getMacAddress();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mac = MacUtil.getMacFromHardware();
        }
        return mac;
    }

        private class GaidAsyncTask extends AsyncTask<DeviceModel,Void,DeviceModel> {

            @Override
            protected DeviceModel doInBackground(DeviceModel... deviceModels) {
                try {
                    AdvertisingIdClient.AdInfo adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context);
                    String gaid =  adInfo.getId();
                    DeviceModel deviceModel = deviceModels[0];
                    deviceModel.setGaid(gaid);
                    return deviceModel;
                }catch (Exception e){
                    Log.e("获取gaid失败:",e.getMessage());
                }
                return deviceModels[0];
            }

            @Override
            protected void onPostExecute(DeviceModel model) {
               super.onPostExecute(model);
               if(onGaidListener!=null){
                   onGaidListener.onSuccess(model);
               }
            }
    }

    public boolean checkPermission(Activity activity){
        if(ContextCompat.checkSelfPermission(activity,permission)
                != PackageManager.PERMISSION_GRANTED){
            return false;
        }else{
            return true;
        }
    }
} 